<template>
	<view class="">
		<image src="../static/logo.png" mode="widthFix"></image>
		<view class="line"></view>
		<view class="title">申请获取以下权限</view>
		<view class="tips">获得你的公开信息(昵称、头像、手机号等)</view>
		<view class="auth_btn" @click="handleAuth">授权登录</view>
		<view class="no_btn" @click="handleNo">暂不登录</view>
	</view>
</template>

<script>
	import request from '@/utils/request.js';
	export default {
		data() {
			return {

			}
		},
		methods: {
			handleAuth() {
				//授权登录
				uni.login({
					success: (loginRes) => {
						if (loginRes.code) {
							// 将登录 code 发送到后端
							this.getUserInfo(loginRes.code);
						} else {
							console.error('登录失败！' + loginRes.errMsg);
						}
					},
					fail: (error) => {
						console.error('登录接口调用失败', error);
					}
				});
			},
			getUserInfo(code) {
				// 获取用户信息
				uni.getAuthCode({
					scopes: ['auth_user'],
					success: (authRes) => {
						console.log(authRes);
						// 将 authRes.code 发送到后端
						this.sendAuthCodeToServer(authRes.authCode);
					},
					fail: (error) => {
						console.error('获取用户信息失败', error);
					}
				});
			},
			async sendAuthCodeToServer(authCode) {
				try {
					const response = await request('/v1/alipay', 'POST', {
						code: authCode,
					},'oauth');
					if (response) {
						uni.setStorageSync("token", response.body.token)
						uni.showToast({
							title: '授权成功'
						})
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/index/index'
							})
						}, 800)
					}
				
				} catch (error) {
					console.error('请求失败:', error);
				}
			},
			handleNo() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		}
	}
</script>

<style>
	image {
		display: block;
		margin: 0 auto;
		width: 300rpx;
		margin-top: 100rpx;
	}

	.line {
		width: 100%;
		height: 1px;
		margin: 30rpx 0;
		background: #f4f4f4;
	}

	.title {
		font-size: 34rpx;
		padding-left: 24rpx;
		margin: 20rpx 0 30rpx 0;
	}

	.tips {
		font-size: 30rpx;
		padding-left: 24rpx;
		color: #666;
	}

	.auth_btn {
		width: 80%;
		height: 88rpx;
		margin: 0 auto;
		background: linear-gradient( 90deg, #4A89EC 0%, #1261E2 100%);
		border-radius: 16rpx;
		margin-top: 60rpx;
		text-align: center;
		color: #fff;
		font-size: 30rpx;
		line-height: 88rpx;
	}

	.no_btn {
		width: 80%;
		height: 88rpx;
		margin: 0 auto;
		background: #999;
		border-radius: 16rpx;
		margin-top: 30rpx;
		text-align: center;
		color: #fff;
		font-size: 30rpx;
		line-height: 88rpx;
	}
</style>